<?php
/**
 * @author    Medard <pingguoli@gmail.com>
 * @date      2019/3/4 15:04
 * @copyright Copyright 2018 - 2019
 *  
 *  
 * @version   1.0
 */

namespace App\Http\Controllers;

use App\Models\Version;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

/**
 * Class LocaleController
 * @package App\Http\Controllers\Web
 */
class LocaleController extends Controller
{
    /**
     * 切换多语言
     * @param $locale
     * @return \Illuminate\Http\RedirectResponse
     */
    public function lang($locale)
    {
        $languages = config('locale.languages');
        if (is_array($languages) && array_key_exists($locale, $languages)) {
            session()->put('locale', $locale);
        }

        return redirect()
            ->back()
            ->withInput();
    }

    /**
     * 文件下载
     * @param $hash
     * @return \Illuminate\Http\RedirectResponse
     */
    public function download($hash){
        $version = Version::where('hash', $hash)->first();
        if (empty($version)){
            return response()->json(['status'=>config("apicode.noRecord.msg"),'msg'=>config("apicode.noRecord.code")]);
        }
        $version->increment('download_num');
        if (count($version->file) == 0){
            return response()->json(['status'=>config("apicode.noRecord.msg"),'msg'=>config("apicode.noRecord.code")]);
        }
        $path = Storage::disk($version->file->disk)->path($version->file->path);
        if (!file_exists($path)){
            Log::error('download error,$hash:'.$path);

            return $this->json([],config("apicode.noRecord.msg"),config("apicode.noRecord.code"));
        }

        return  response()->download($path);
    }
}
